package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired
    JedisPool jedisPool;

    @RequestMapping("/order")
    public Result sendValidateCode4Order(@RequestBody String phoneNumber) {
        String code = ValidateCodeUtils.generateValidateCode(4);
        System.out.println(code);
        try {
            SMSUtils.sendSMS("+86" + phoneNumber, code);
            jedisPool.getResource().setex(phoneNumber + RedisConstant.Validate_Code_Order, 5000, code);
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    @RequestMapping("/send4Login")
    public Result sendValidateCode4Login(@RequestBody String phoneNumber) {
        String code = ValidateCodeUtils.generateValidateCode(6);
        System.out.println(code);
        try {
            SMSUtils.sendSMS("+86" + phoneNumber, code);
            jedisPool.getResource().setex(phoneNumber + RedisConstant.Validate_Code_Login, 5000, code);
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }
}
